from django.shortcuts import render
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from datetime import datetime
from common.models import Goods,Types,Orders,Detail

# 商品导航信息加载
def loadPNav(request):
    '''商品导航信息加载'''
    context={}
    plists=Types.objects.filter(pid=0)
    print(plists)
    context["typelist"]=plists
    return context

def add(request):
    '''下订单'''
    context=loadPNav(request)
    print(request.session["vipuser"])
    #获取要结算的商品id
    gids=request.GET.get("ids","")
    if len(gids)==0:
        context={"info":"请选择要结算的商品！"}
        return render(request,"web/ordersinfo.html",context)
    gidlist=gids.split(",")

    #从购物车获取要结算的商品信息，放入ordesrlist，累计总金额
    shoplist=request.session["shoplist"]
    orderslist={}
    total=0
    for id in gidlist:
        temp_shop=shoplist[id]
        orderslist[id]=temp_shop
        total+=temp_shop["price"] * temp_shop["m"]
    # 将订单信息放入session
    request.session["orderslist"]=orderslist
    request.session["totalMoney"]=total
    return render(request,"web/ordersadd.html",context)

def confirm(request):
    '''订单确认'''
    context=loadPNav(request)
    return render(request,"web/ordersconfirm.html",context)

def insert(request):
    '''确认下单'''
    context=loadPNav(request)
    try:
        orderOBJ=Orders()
        orderOBJ.uid=request.session["vipuser"]["id"]# 会员id
        orderOBJ.linkman=request.POST.get("linkman")
        orderOBJ.address = request.POST.get("address")
        orderOBJ.code = request.POST.get("code")
        orderOBJ.phone = request.POST.get("phone")
        orderOBJ.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        orderOBJ.total = request.session["totalMoney"]
        orderOBJ.state = 0
        orderOBJ.save()
        #订单详情 下单成功后，将商品从购物车删除
        orderslist=request.session["orderslist"]
        shoplist=request.session["shoplist"]
        print(orderslist.values())
        for shop in orderslist.values():
            del shoplist[str(shop["id"])]
            detailOBJ=Detail()
            detailOBJ.orderid=orderOBJ.id
            detailOBJ.goodsid = shop["id"]
            detailOBJ.name = shop["goods"]
            detailOBJ.price = shop["price"]
            detailOBJ.num = shop["m"]
            detailOBJ.save()
        del request.session["orderslist"]
        del request.session["totalMoney"]
        request.session["shoplist"]=shoplist
        context={"info":"订单添加成功！订单号："+str(orderOBJ.id)}
        return render(request,"web/ordersinfo.html",context)
    except Exception as err:
        print("错误",err)
        context={"info":"订单添加失败，请稍后再试！"}
        return render(request, "web/ordersinfo.html", context)